package com.lihan.GetSeatInLib.Service.impl;

import java.util.Date;
import java.util.HashMap;
import java.util.concurrent.TimeUnit;

import javax.annotation.Resource;
import javax.mail.MessagingException;
import javax.servlet.http.HttpSession;
import javax.transaction.Transactional;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.stereotype.Service;

import com.lihan.GetSeatInLib.Domain.User;
import com.lihan.GetSeatInLib.Domain.MailModel.MailTemplate;
import com.lihan.GetSeatInLib.Repository.UserRepository;
import com.lihan.GetSeatInLib.Service.MailService;
import com.lihan.GetSeatInLib.Service.UserService;
import com.lihan.GetSeatInLib.Tools.CommonFinal;
import com.lihan.GetSeatInLib.Tools.MyEncoder;
import com.lihan.GetSeatInLib.Tools.PassTokenAnnoation;

@Service
public class UserServiceImpl implements UserService{
	
	@Autowired
	@Qualifier("redisTemplate")
	private RedisTemplate<String, String> redisTemplate;
	
	@Autowired
	private UserRepository _userdao;
	
	@Autowired
	private MyEncoder encoder; //加密工具
	
	@Autowired
	private MailService mailService; //邮件工具
	
	@Override
	@Cacheable(cacheNames = "UserCache",key = "#ID")
	public User getUserInfoByID(long ID) {
		User user = _userdao.getById(ID);
		return user;
	}
	
	@Override
	@Cacheable(cacheNames = "UserCache",key = "#UserName")
	public User getUserInfoByUserName(String UserName) {
		User user = _userdao.getUserByName(UserName);
		return user;
	}

	//注册新用户
	@Transactional
	@Override
	public void InsertNewUser(User user) {
		user.setPassword(encoder.Encoder(user.getPassword())); //插入的密码可以加下密
		_userdao.save(user);
		
	}

	/**
	 * 检查用户登录的用户名和密码
	 */
	@PassTokenAnnoation
	@Cacheable(cacheNames = "LoginerCache",key = "#UserName",condition = "#result!=null")
	@Override
	public User LoginWirhPassword(String UserName, String password) {
			
		//检查账号密码是否一致
		User user = _userdao.LoginCheck(UserName,password);
		System.out.println("TMD："+user==null);

		return user;
	}

	/**
	 * 更新用户密码
	 */
	@Override
	public Boolean FixPassword(String UserName,String OldPassword, String NewPassword,String VeriferCode) {
		
		//执行修改密码前先验证发送的验证码
		//到Redis中找验证码并比对
		ValueOperations<String, String> getVCode = redisTemplate.opsForValue();
		if(getVCode.get(UserName+"::VeriferCode")==null)
			return false;
		if(!VeriferCode.equals(getVCode.get(UserName+"::VeriferCode")))
			return false;
		
		User nowLoginer = _userdao.getUserByName(UserName);
		nowLoginer.setPassword(encoder.Encoder(NewPassword));
		if(_userdao.save(nowLoginer) != null)
			return true;
		else 
			return false;
	}
	
	
	/**
	 * 验证码放在Redis缓存里，设置一段时间再过期
	 */
	@Override
	public Boolean SendFixPasswordMail(String UserName) throws MessagingException {
		
		//先获取验证码
		String VerifyCode = MailService.ProductVerifyCode();
		//获取要发送给用户的信息（获取User信息）
		User user = _userdao.getUserByName(UserName);
		
		MailTemplate template = new MailTemplate();
		template.setFrom(CommonFinal.SENDER_MAIL);
		template.setTo(user.getEmail());
		template.setVerifyCode(VerifyCode);
		template.setSendDate(new Date());
		template.setTitle("密码修改验证短信");
		HashMap<String, String> map = new HashMap<String, String>();
		map.put("OperationName", "修改密码");
		map.put("VerifyCode", VerifyCode);
		template.setContext(map);
		
		//存入Redis,放置5分钟
		ValueOperations<String, String> ops = redisTemplate.opsForValue();
        ops.set(UserName+"::VeriferCode", VerifyCode,5,TimeUnit.MINUTES);
        
		return mailService.SendMail(template,"Mail.html");
		
	}
}
